/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.main;

import com.koron.common.PersonResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.MultipartConfigElement;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 该注解指定项目为springboot，由此类当作程序入口 自动装配 web 依赖的环境
 **/
@SpringBootApplication(scanBasePackages = {"com.koron"})
@EnableSwagger2
public class App extends WebMvcConfigurationSupport {
    private final static Logger logger= LoggerFactory.getLogger(App.class);
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(App.class);
        ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
        Environment environment = context.getBean(Environment.class);
        logger.info("数据库连接URL:"+environment.getProperty("spring.datasource.safety.base.jdbc-url"));
        logger.info("数据库连接账号:"+environment.getProperty("spring.datasource.safety.base.username"));
        logger.info("数据库连接密码:"+environment.getProperty("spring.datasource.safety.base.password"));
        /*Banner b = new Banner() {
            @Override
            public void printBanner(Environment environment, Class<?> sourceClass, PrintStream printStream) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("logo.txt")));
                String tmp = null;
                try {
                    while ((tmp = reader.readLine()) != null)
                        printStream.println(tmp);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                printStream.print("App version is:" + AnsiOutput.toString(AnsiColor.RED, environment.getProperty("app.version")) + "  ");
                String version = SpringBootVersion.getVersion();
                version = (version == null ? "" : " (v" + version + ")");
                printStream.println(AnsiOutput.toString(AnsiColor.GREEN, "Spring Boot:" + version));
            }
        };
        app.setBanner(b);*/
        //app.run(args);
    }

    /**
     * 上传附件容量限制
     *
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("10240000KB");
        factory.setMaxRequestSize("11240000KB");
        return factory.createMultipartConfig();
    }

    /*
     * 装载session
     * (non-Javadoc)
     * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#addArgumentResolvers(java.util.List)
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        super.addArgumentResolvers(argumentResolvers);
        argumentResolvers.add(new PersonResolver());
    }


    /**
     * 解决浏览器中文乱码问题
     *
     * @return
     */
    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        return converter;
    }

    @Bean
    public InternalResourceViewResolver setupViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setSuffix(".html");
        return resolver;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        converters.add(responseBodyConverter());
        converters.add(new ByteArrayHttpMessageConverter());
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("*")
                .allowedHeaders("*")
                .exposedHeaders("Header1", "Header2");
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        //注册自己的拦截器并设置拦截的请求路径
        registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/static/**")
                .excludePathPatterns("/web/**")
                .excludePathPatterns("/mobile/**")
                .excludePathPatterns("/staff/updatePwd.htm")
                .excludePathPatterns("/verifyCode/getCode.htm")
                .excludePathPatterns("/getWxConfigByWxCp.htm")
                .excludePathPatterns("/getWxConfig.htm")
                .excludePathPatterns("/redirectoauth2.htm")
                .excludePathPatterns("/redirectoauth.htm")
                .excludePathPatterns("/callback.htm")
                .excludePathPatterns("/dangerousOperation/saveByQrCode.htm")
                .excludePathPatterns("/dangerousOperation/getSecret")
                .excludePathPatterns("/dangerousOperation/syncSave.htm")
                .excludePathPatterns("/dangerousOperation/getAllSafetyMeasure.htm")
                .excludePathPatterns("/dangerousOperation/getAllProtectionAndEmergency.htm")
                .excludePathPatterns("/dangerousOperation/getAllRiskIdentificationAndMeasures.htm")
                .excludePathPatterns("/dangerousOperation/getAllOperationType.htm")
                .excludePathPatterns("/workFlowDeptAndStaff/toWorkFlowStaffList.htm")
                .excludePathPatterns("/workFlowDeptAndStaff/toWorkFlowDepartmentList.htm")
                .excludePathPatterns("/cas.htm")
                .excludePathPatterns("/operationActivity/detail.htm")
                .excludePathPatterns("/operationActivity/listOperationTicket.htm")
                .excludePathPatterns("/operationActivity/queryOperationTicketById.htm")
                .excludePathPatterns("/operationActivity/exportOperationTicket.htm")
                .excludePathPatterns("/operationActivity/saveOperationTicketByQrCode.htm")
                .excludePathPatterns("/getUserInfo.htm");
        super.addInterceptors(registry);
    }
}
